package com.yjj.demo.common.utils;

import com.yjj.demo.common.exception.NoStackException;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 *
 *
 * @author yangjiajia
 * @createdAt 2023/2/10 15:08
 */
public class RandomUtil {

    public static <T> T randomKey(Map<T, Integer> randomMap) {
        if (CollectionUtils.isEmpty(randomMap)) {
            throw new NoStackException("随机元素为空");
        }
        Random random = new Random();
        int sum = randomMap.values().stream().mapToInt(Integer::intValue).sum();
        int randomNum = random.nextInt(sum);
        int numSum = 0;
        for (T key : randomMap.keySet()) {
            int value = randomMap.get(key);
            numSum += value;
            if (randomNum <= numSum) {
                return key;
            }
        }
        return null;
    }

    public static void main(String[] args) {

        Map<String, Integer> counterMap = new HashMap<>();

        for (int i = 1; i <= 10000; i ++) {
            Map<String, Integer> map = new HashMap<>();
            map.put("a", 10);
            map.put("b", 100);
            map.put("c", 1000);
            String result = RandomUtil.randomKey(map);

            int count = counterMap.getOrDefault(result, 0);
            count++;
            counterMap.put(result, count);
        }

        for (String key : counterMap.keySet()) {
            System.out.println("key:" + key + ",count:" + counterMap.get(key));
        }
    }
}
